//
//  LoginViewController.m
//

#import "LoginViewController.h"
#import "ProtocolAgreeView.h"

#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>

@interface LoginViewController ()<UITextFieldDelegate>

@property (nonatomic) CreditTextFiled *phoneFiled,*captureFiled;
@property (nonatomic) UIButton *captureBtn,*loginBtn;
@property (nonatomic) NSTimer * timer;
@property (nonatomic) BOOL agree;


@property (nonatomic) BOOL isNetworkError;

@end

static int timeCount = 60;

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [self judgeNet];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)textfiledNotif{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initUI];

    [self textfiledNotif];
}

- (void)cancelBtnClick{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:^{
            
    }];
}

- (void)initUI{
    
    UIImage *icon = [UIImage imageNamed:@"icon_login_bg"];
    UIImageView *iconV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, icon.size.height)];
    iconV.image = icon;
    [self.view addSubview:iconV];
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, kNavigationBarHeight - 30, 40, 40)];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_close_black"] forState:UIControlStateNormal];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_close_black"] forState:UIControlStateSelected];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_close_black"] forState:UIControlStateHighlighted];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:cancelBtn];
    
    
    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(30, kNavigationBarHeight  + 30, 40, 40)];
    logo.image = [UIImage imageNamed:@"icon_logo"];
    [self.view addSubview:logo];
    
    UILabel *lab = [Utility createLabel:[UIFont fontWithName:kFutura size:20] color:[UIColor colorWithHexString:@"#022D06"]];
    
    lab.text = [NSString stringWithFormat:@"%@\n%@",@"HELLO,",@"Welcome To Log In Mabilis Money"];
        
//    lab.attributedText = [StringUtil setText:[NSString stringWithFormat:@"%@\n%@",@"HELLO,",@"Welcome To Log In Mabilis Money"] lineSpacing:35 font:[UIFont fontWithName:kFutura size:20] withAlignment:0];
    
    [self.view addSubview:lab];

    lab.frame = CGRectMake(30, logo.bottom + 10, kScreenWidth, 80);
    
    [lab addAttributesArray:@[@{NSFontAttributeName:[UIFont fontWithName:kFutura size:26]},
                              @{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#00BA60"]}] forStringArray:@[@"HELLO,",@"Mabilis Money"]];
    
    lab.numberOfLines = 0;
    
    
    
    
    
    
    /*
     Futura-Medium
     Futura-MediumItalic
     Futura-Bold
     Futura-CondensedMedium
     Futura-CondensedExtraBold
     
     FuturaBT-Medium
     FuturaBT-Book
     */
    
    
    
    self.phoneFiled = [[CreditTextFiled alloc]init];
    self.phoneFiled.frame = CGRectMake(lab.left, lab.bottom + 25, kScreenWidth - 64, 50);
    self.phoneFiled.limitedCount = 26;
    self.phoneFiled.delegate = self;
    self.phoneFiled.font = [UIFont fontWithName:kFuturaMedium size:15];
    self.phoneFiled.placeholder = @"Enter your cellphone number";
    self.phoneFiled.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneFiled.drawBottomLine = YES;
    self.phoneFiled.textColor = [UIColor colorWithHexString:@"#022D06"];
    [self.view addSubview:self.phoneFiled];
    self.phoneFiled.tintColor = kButtonRedColor;
    [self.phoneFiled addLeftViewWithTitle:@"+63" leftMargin:15 leftWidth:60 leftColor:[UIColor colorWithHexString:@"#00BA60"] leftFont:[UIFont fontWithName:kFuturaMedium size:15] leftViewMode:UITextFieldViewModeAlways];
    
    self.phoneFiled.layer.cornerRadius = 50/2;
    self.phoneFiled.layer.masksToBounds = YES;
    self.phoneFiled.layer.borderWidth = 1;
    self.phoneFiled.layer.borderColor = kButtonRedColor.CGColor;
    
    
    NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:self.phoneFiled.placeholder attributes:@{NSFontAttributeName : [UIFont fontWithName:kFutura size:13],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#638473"]}];
    self.phoneFiled.attributedPlaceholder = placeholderString;
    
    if (!PMStringIsEmpty([[NSUserDefaults standardUserDefaults] valueForKey:kUserNameKey])) {
        self.phoneFiled.text = esString([[NSUserDefaults standardUserDefaults] valueForKey:kUserNameKey]);
    }
    

    self.captureFiled = [[CreditTextFiled alloc]init];
    self.captureFiled.frame = CGRectMake(lab.left, self.phoneFiled.bottom + 30, kScreenWidth - 64, 50);
    self.captureFiled.limitedCount = 6;
    self.captureFiled.delegate = self;
    self.captureFiled.font = [UIFont fontWithName:kFuturaMedium size:15];
    self.captureFiled.placeholder = @"Enter The Confirmation Code";
    self.captureFiled.keyboardType = UIKeyboardTypeNumberPad;
    self.captureFiled.drawBottomLine = YES;
    self.captureFiled.textColor = [UIColor colorWithHexString:@"#022D06"];
    [self.view addSubview:self.captureFiled];
    self.captureFiled.tintColor = kButtonRedColor;
    
    [self.captureFiled addLeftViewWithTitle:@"+6" leftMargin:10 leftWidth:20 leftColor:[UIColor clearColor] leftFont:[UIFont systemFontOfSize:16] leftViewMode:UITextFieldViewModeAlways];
    
    NSMutableAttributedString *placeholderCapString = [[NSMutableAttributedString alloc] initWithString:self.captureFiled.placeholder attributes:@{NSFontAttributeName : [UIFont fontWithName:kFutura size:13],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#638473"]}];
    self.captureFiled.attributedPlaceholder = placeholderCapString;
    
    self.captureFiled.layer.cornerRadius = 50/2;
    self.captureFiled.layer.masksToBounds = YES;
    self.captureFiled.layer.borderWidth = 1;
    self.captureFiled.layer.borderColor = kButtonRedColor.CGColor;
    
    UIButton *getCaptchaButton = [[UIButton alloc]initWithFrame:CGRectMake(self.captureFiled.right - 15 - 100, self.captureFiled.top, 100, 50)];
    self.captureBtn = getCaptchaButton;
    [self.view addSubview:self.captureBtn];
    [getCaptchaButton setTitle:@"Send Code" forState:UIControlStateNormal];
    [getCaptchaButton setTitleColor:kButtonRedColor forState:UIControlStateNormal];
    getCaptchaButton.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:14];
    [getCaptchaButton addTarget:self action:@selector(getCaptchaCode) forControlEvents:UIControlEventTouchUpInside];
    getCaptchaButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(getCaptchaButton.left + 20, self.captureFiled.top + 18, 1, 14)];
    line.backgroundColor = [UIColor colorWithHexString:@"#F1F3F2"];
    [self.view addSubview:line];
    
    self.loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(lab.left, self.captureFiled.bottom + 40, kScreenWidth - lab.left*2, DimensionBaseIphone6(kGeneralHeight))];
    [self.loginBtn setTitle:@"Login" forState:UIControlStateNormal];
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.loginBtn addTarget:self action:@selector(clickLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    self.loginBtn.enabled = NO;
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateSelected];
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateHighlighted];
    

    NSString *textStr = @"I have read and agree Privacy Agreement";
    CGRect rec = [textStr boundingRectWithSize:CGSizeMake(kScreenWidth - 32, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} context:nil];
    
    ProtocolAgreeView *agreeView = [[ProtocolAgreeView alloc]initWithTitle:@"I have read and agree " withTitleColor:[UIColor colorWithHexString:@"#638473"] protocol:@"Privacy Agreement" withProtocolColor:kButtonRedColor fontSize:13 target:self withSel:YES withAgreeImg:@"icon_agree" withUnagreeImg:@"icon_unagree"];
    agreeView.frame = CGRectMake((kScreenWidth - rec.size.width - 25)/2, self.loginBtn.bottom  + 30, rec.size.width + 25, 20);
    [self.view addSubview:agreeView];
    
    self.agree = YES;
    
    
}

- (void)agreeViewWillShowProtocol{
    BaseWebViewController *vc = [[BaseWebViewController alloc] init];
    vc.urlStr = [NSString stringWithFormat:@"%@",kPricateUrl];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)agreeViewWillAgreeProtocol:(BOOL)agree{
    self.agree = agree;
}

-(void)didChange:(NSNotification *)notification{
    NSString *phoneStr = [self.phoneFiled.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (phoneStr.length > 0  && !PMStringIsEmpty(self.captureFiled.text)) {
        self.loginBtn.enabled = YES;
        [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login1"] forState:UIControlStateNormal];
        [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login1"] forState:UIControlStateSelected];
        [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login1"] forState:UIControlStateHighlighted];
        
//        if (self.captureFiled.text.length == 6) {
//            [self clickLogin];
//        }
        
        
        return;
    }
    self.loginBtn.enabled = NO;
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateSelected];
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateHighlighted];
}


- (void)textFieldDidChangeSelection:(UITextField *)textField{
    if (textField == self.captureFiled) {
        if (self.captureFiled.text.length == 6) {
            [self clickLogin];
        }
    }
}


#pragma mark textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    self.loginBtn.enabled = NO;
    self.loginBtn.alpha = 0.35;
    return YES;
}


#pragma mark login
- (void)clickLogin{

    [self.view endEditing:YES];

    if (!self.agree) {
        [CreaditUtilsHelper boxShowWithMessage:@"Please read the agreement and agree to it"];
        return;
    }
    
    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"fancy":esString(self.phoneFiled.text),
        @"wider":esString(self.captureFiled.text),
        @"gulf":@"login"
    }.mutableCopy;
    
    [BaseDataEngine apiForPath:kLoginUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        DLog(@"=====%@",responseDic);
        [CreaditUtilsHelper hideLoadMessageBox];
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        
        NSDictionary *dataDic = responseDic[@"recollecting"];
        
        [CurrentUser mine].userInfo = [UserInfoModel mj_objectWithKeyValues:dataDic];
        
        [CurrentUser loginSuccess:esString(dataDic[@"brightly"])];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationMsg_Land_Sucess object:nil];
        
        if (self.navigationController.finishBlock) {
            self.navigationController.finishBlock();
        }
       
//        [self dismissViewControllerAnimated:YES completion:nil];
        MainTabBarController *tabBar = [[MainTabBarController alloc]init];
        [[CreditCore mainWindow] setRootViewController:tabBar];
        
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserNameKey];
        [[NSUserDefaults standardUserDefaults] setValue:esString(self.phoneFiled.text) forKey:kUserNameKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        

        [CreditServerHelper uploadMaiDianDataStartTimeStr:self.startTimeStr andEndTimeStr:[NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"] withTypeStr:@"1" withFirmly:@"" withSmaller:@""];
        
        [[NSUserDefaults standardUserDefaults] setObject:esString(self.startTimeStr) forKey:kRecStartTime];
        [[NSUserDefaults standardUserDefaults] setObject:[NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"] forKey:kRecEndTime];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
        [CreaditUtilsHelper boxShowErrorWithMessage:error.localizedDescription duration:2.5f];
        
    } withIsForm:YES];
    
    
}

-(void)getCaptchaCode{
    if (PMStringIsEmpty(self.phoneFiled.text)) {
        [CreaditUtilsHelper boxShowWithMessage:@"Please enter your phone number"];
        return;
    }
    [self startTimer];
}

- (void)startTimer{
    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"upward":esString(self.phoneFiled.text),
        @"clearly":@"clearlyCapture"
    }.mutableCopy;
    
    [BaseDataEngine apiForPath:kCaptureUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic){
        [CreaditUtilsHelper hideLoadMessageBox];
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        
        self.captureBtn.enabled = NO;
        if (!self.timer) {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(upateTime) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }
        [self.timer fire];
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
    } withIsForm:YES];
    
    
}

- (void)upateTime{
    NSString * timeString = [NSString stringWithFormat:@"%ds", timeCount--];
    [self.captureBtn setTitle:timeString forState:UIControlStateDisabled];
    if (timeCount == 0) {
        [self stopTimer];
    }
}

- (void)stopTimer{
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    if(self.captureBtn){
        self.captureBtn.enabled = YES;
        [self.captureBtn setTitle:@"Send Code" forState:UIControlStateNormal];
        timeCount = 60;
    }
    
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)judgeNet{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 1 || status == 2){
            self.isNetworkError = NO;
        }
        else{
            self.isNetworkError = YES;
        }
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    if (!self.isNetworkError) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self isOpenIdfa];
        });
    }
    
    
    
}

- (void)isOpenIdfa{
    
    if (@available(iOS 14,*)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            
            NSString *idfaStr = @"";
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                
                idfaStr = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
                DLog(@"==idfaStr==%@",idfaStr);
                
            } else {
                DLog(@"do not open idfa");
            }
            [self uploadIdfaData:idfaStr];
            
            [[NSUserDefaults standardUserDefaults] setValue:esString(idfaStr) forKey:kIDFAStr];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            DLog(@"--idfv---%@\n--idfa--%@",[UIDevice currentDevice].identifierForVendor.UUIDString,idfaStr);
        }];
        
    }
    else {
    
        NSString *idfaStr = @"";
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            idfaStr = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
            DLog(@"==idfaStr==%@",idfaStr);
            [self uploadIdfaData:idfaStr];
        }
        else {
            DLog(@"do not open idfa");
        }
        [[NSUserDefaults standardUserDefaults] setValue:esString(idfaStr) forKey:kIDFAStr];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self uploadIdfaData:idfaStr];
        
        
        DLog(@"--idfv---%@\n--idfa--%@",[UIDevice currentDevice].identifierForVendor.UUIDString,idfaStr);
    }
    
    
    
    
}

- (void)uploadIdfaData:(NSString *)idfaStr{
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:kLoginIDFA]) {
        NSMutableDictionary *muDic = @{
            @"eighteen":@"eighteenGoogle",
            @"devil":esString([UIDevice currentDevice].identifierForVendor.UUIDString),
            @"hit":esString(idfaStr),
        }.mutableCopy;
        [BaseDataEngine apiForPath:kUploadGoogleUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
            if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
                return;
            }
            DLog(@"=====upload idfa success=====");
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kLoginIDFA];
            [[NSUserDefaults standardUserDefaults] synchronize];
        } onCompleteFailur:^(NSError *error) {
            
        } withIsForm:YES];
    }
    
}

@end
